<template>
    <BaseContent>
        <div class="card card_single" v-for="book in recently_visit_books.recently_visit_books[currentIndex]" :key="book.id">
            <div class="card-body">
                <span>书名：{{ book.title }}</span>
                <span>作者：{{ book.author }}</span>
                <span>出版社：{{ book.publisher }}</span>
                <span>库存：{{ book.stock }}</span>
                <button type="button" class="btn btn-primary" @click="open(book.id, book.title, book.author, book.stock, book.photo, book.description, book.score, book.book_type, book.awarded, book.publisher)" v-if="book.stock >= 1 && !is_borrowed(book.title)">
                    我要借阅
                </button>
                <button type="button" class="btn btn-danger" @click="open_return(book.id, book.title, book.stock, book.score, book.photo, book.author, book.description, book.book_type, book.awarded, book.publisher)" v-if="is_borrowed(book.title)">
                    申请还书
                </button>
                <button type="button" class="btn btn-warning" v-if="book.stock <= 0 && !is_borrowed(book.title)">库存不足</button>
                <button type="button" class="btn btn-success" @click="open_a_book(book.id, book.score, book.stock, book.title, book.photo, book.author, book.description, book.book_type, book.awarded)">
                    图书详情
                </button>
            </div>
            <div class="tanchuang" v-if="is_open">
                <div class="mb-3">
                    <div class="info_confirm">请确认学号是否正确</div>
                    <input type="text" class="form-control" :placeholder="$store.state.user.username" disabled>
                    <div class="info_confirm">请确认是否是所借书籍</div>
                    <input type="text" class="form-control" :placeholder="borrowed_bookname" disabled>
                </div>
                <button type="button" class="btn btn-success btn-tanchuang btn-1" @click="borrow_a_book">确定</button>
                <button type="button" class="btn btn-danger btn-tanchuang btn-2" @click="close">取消</button>
            </div>
            <div class="tanchuang" v-if="is_open_return">
                <div class="mb-3">
                    <div class="info_confirm">请确认学号是否正确</div>
                    <input type="text" class="form-control" :placeholder="$store.state.user.username" disabled>
                    <div class="info_confirm">请确认是否是所还书籍</div>
                    <input type="text" class="form-control" :placeholder="return_bookname" disabled>
                </div>
                <button type="button" class="btn btn-success btn-tanchuang btn-1" @click="return_a_book">确定</button>
                <button type="button" class="btn btn-danger btn-tanchuang btn-2" @click="close">取消</button>
            </div>
        </div>
        <nav aria-label="Page navigation example book-pagination">
            <ul class="pagination">
                <li class="page-item" :class="{ disabled: currentIndex === 0 }">
                    <a class="page-link" href="#" @click="go_to_page(currentIndex - 1)">上一页</a>
                </li>
                <li class="page-item" v-for="index in pageCount" :key="index" :class="{ active: index - 1 === currentIndex }">
                    <a class="page-link" href="#" @click="go_to_page(index - 1)">{{ index }}</a>
                </li>
                <li class="page-item" :class="{ disabled: currentIndex === pageCount - 1 }">
                    <a class="page-link" href="#" @click="go_to_page(currentIndex + 1)">下一页</a>
                </li>
            </ul>
        </nav>
    </BaseContent>
</template>
<script>
import BaseContent from '@/components/BaseContent.vue';
import { ref, reactive } from 'vue';
import $ from 'jquery';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import dayjs from 'dayjs';

export default {
    name: "LiteratureView",
    components: {
        BaseContent,
    },
    setup() {
        let LiteratureBooks = ref([]);
        const router = useRouter();
        const store = useStore();
        const is_open = ref(false);
        const borrowedbooks = ref([]);
        const borrowed_book_id = ref('');
        const return_book_id = ref('');
        const borrowed_bookname = ref('');
        const return_bookname = ref('');
        const borrowed_bookauthor = ref('');
        const is_open_return = ref(false);
        const book_photo = ref('');
        const book_description = ref('');
        const book_score = ref('');
        const book_stock = ref('');
        const return_book_stock = ref('');
        const return_book_score = ref('');
        const book_user_ranking = reactive({});
        const return_book_photo = ref('');
        const return_book_author = ref('');
        const return_book_description = ref('');
        const recently_visit_books = reactive({recently_visit_books: []});
        const borrowed_book_book_type = ref('');
        const borrowed_book_awarded = ref('');
        const return_book_type = ref('');
        const return_book_awarded = ref('');
        const apply_return_list = ref([]);
        const return_book_publisher = ref('');
        const borrowed_book_publisher = ref('');
        const formattedDate = dayjs().format('YYYY-MM-DD HH:mm:ss');
        let pageCount = ref(0);
        let currentIndex = ref(0);

        $.ajax({
            url: 'http://47.121.28.202:8000/settings/getbooks/',
            type: "GET",
            success(resp) {
                for (let book of resp) {
                    if (book.book_type === "文学") {
                        LiteratureBooks.value.push(book);
                    }
                }
                let currentPage = [];
                for (let i of LiteratureBooks.value) {
                    if (currentPage.length < 15) {
                        currentPage.push(i);
                    } else {
                        recently_visit_books.recently_visit_books.push(currentPage);
                        currentPage = [i];
                    }
                }
                if (currentPage.length > 0) {
                    recently_visit_books.recently_visit_books.push(currentPage);
                }
                pageCount.value = recently_visit_books.recently_visit_books.length;
            }
        })

        const go_to_page = (pageIndex) => {
            if (pageIndex >= 0 && pageIndex < pageCount.value) {
                currentIndex.value = pageIndex;
            }
        }

        $.ajax({
            url: "http://47.121.28.202:8000/settings/ranking/",
            type: "GET",
            headers: {
                'Authorization': "Bearer " + store.state.user.access,
            },
            data: {
                user_id: store.state.user.id,
            },
            success(resp) {
                book_user_ranking.count = resp.length,
                book_user_ranking.book_user_ranking = resp;
            }
        })

        const open_a_book = (bookid, scorex, stock, titlex, photox, authorx, descriptionx, book_type, book_awarded) => {
            if(store.state.user.is_login) {
                router.push({
                    name: 'bookinfo',
                    params: {
                        bookid
                    }
                })
                $.ajax({
                    url: 'http://47.121.28.202:8000/settings/getbooks/',
                    type: "PATCH",
                    data: {
                        book_id: bookid,
                        stock: stock,
                        score: scorex + 4,
                    },
                })
                for (let i of book_user_ranking.book_user_ranking) {
                    if(i.book_title === titlex) {
                        $.ajax({
                            url: 'http://47.121.28.202:8000/settings/ranking/',
                            type: "PATCH",
                            headers: {
                                'Authorization': "Bearer " + store.state.user.access,
                            },
                            data: {
                                book_score: i.book_score + 8,
                                book_id: i.book_id,
                                user_id: store.state.user.id,
                                visittime: formattedDate,
                            },
                        })
                        return
                    }
                }
                $.ajax({
                    url: 'http://47.121.28.202:8000/settings/ranking/',
                    type: "POST",
                    headers: {
                        'Authorization': "Bearer " + store.state.user.access,
                    },
                    data: {
                        user_id: store.state.user.id,
                        book_id: bookid,
                        book_title: titlex,
                        user_username: store.state.user.username,
                        visittime: formattedDate,
                        photo: photox,
                        description: descriptionx,
                        author: authorx,
                        book_type: book_type,
                        book_awarded: book_awarded,
                    },
                    success(resp) {
                        console.log(resp);
                        $.ajax({
                            url: 'http://47.121.28.202:8000/settings/ranking/',
                            type: "PATCH",
                            headers: {
                                'Authorization': "Bearer " + store.state.user.access,
                            },
                            data: {
                                book_score: 6,
                                book_id: bookid,
                                user_id: store.state.user.id,
                                visittime: formattedDate,
                            },
                        })
                    }
                })
            } else {
                router.push({
                    name: 'login',
                })
            }
        }

        const open = (book_idx, booknamex, bookauthorx, stock, photox, descriptionx, scorex, book_type, book_awarded, book_publisher) => {
            if (store.state.user.is_login) {
                is_open.value = true;
                borrowed_book_id.value = book_idx;
                borrowed_bookname.value = booknamex;
                borrowed_bookauthor.value = bookauthorx;
                book_photo.value = photox;
                book_score.value = scorex;
                book_stock.value = stock;
                book_description.value = descriptionx;
                borrowed_book_book_type.value = book_type;
                borrowed_book_awarded.value = book_awarded;
                borrowed_book_publisher.value = book_publisher;
            }
            else {
                router.push({
                    name: 'login',
                })
            }
        }
        const open_return = (book_idx, booknamex, stockx, scorex, photox, authorx, descriptionx, book_type, book_awarded, publisher) => {
            return_book_id.value = book_idx;
            return_bookname.value = booknamex;
            return_book_stock.value = stockx;
            return_book_score.value = scorex;
            return_book_photo.value = photox;
            return_book_author.value = authorx;
            return_book_description.value = descriptionx;
            return_book_type.value = book_type;
            return_book_awarded.value = book_awarded;
            return_book_publisher.value = publisher;
            is_open_return.value = true;
        }
        const close = () => {
            is_open.value = false;
            is_open_return.value = false;
        }

        $.ajax({
            url: "http://47.121.28.202:8000/settings/borrowedbooks/",
            type: "GET",
            data: {
                user_id: store.state.user.id,
            },
            headers: {
                'Authorization': "Bearer " + store.state.user.access,
            },
            success(resp) {
                borrowedbooks.value = resp;
            }
        })

        const add_score = () => {
            const is_have_borrowed_book = ref(false);
            for (let i of book_user_ranking.book_user_ranking) {
                if(i.book_title === borrowed_bookname.value) {
                    is_have_borrowed_book.value = true;
                }
            }
            if (is_have_borrowed_book.value) {
                $.ajax({
                    url: 'http://47.121.28.202:8000/settings/ranking/',
                    type: "PATCH",
                    headers: {
                        'Authorization': "Bearer " + store.state.user.access,
                    },
                    data: {
                        book_score: parseInt(book_score.value) + 8,
                        book_id: parseInt(borrowed_book_id.value),
                        user_id: store.state.user.id,
                        visittime: formattedDate,
                    },
                })
            } else {
                $.ajax({
                    url: 'http://47.121.28.202:8000/settings/ranking/',
                    type: "POST",
                    headers: {
                        'Authorization': "Bearer " + store.state.user.access,
                    },
                    data: {
                        user_id: store.state.user.id,
                        book_id: parseInt(borrowed_book_id.value),
                        book_title: borrowed_bookname.value,
                        user_username: store.state.user.username,
                        visittime: formattedDate,
                        photo: book_photo.value,
                        description: book_description.value,
                        author: borrowed_bookauthor.value,
                        book_type: borrowed_book_book_type.value,
                        book_awarded: borrowed_book_awarded.value,
                    },
                    success(resp) {
                        console.log(resp);
                        $.ajax({
                            url: 'http://47.121.28.202:8000/settings/ranking/',
                            type: "PATCH",
                            headers: {
                                'Authorization': "Bearer " + store.state.user.access,
                            },
                            data: {
                                book_score: 6,
                                book_id: parseInt(borrowed_book_id.value),
                                user_id: store.state.user.id,
                                visittime: formattedDate,
                            }
                        })
                    }
                })
            }
        }

        const borrow_a_book = () => {
            add_score();
            $.ajax({
                url: "http://47.121.28.202:8000/settings/borrowedbooks/",
                type: "POST",
                headers: {
                    'Authorization': "Bearer " + store.state.user.access,
                },
                data: {
                    photo: book_photo.value,
                    user_id: store.state.user.id,
                    book_id: parseInt(borrowed_book_id.value),
                    bookname: borrowed_bookname.value,
                    bookauthor: borrowed_bookauthor.value,
                    studentid: store.state.user.username,
                    borrowedtime: formattedDate,
                    description: book_description.value,
                    is_apply: "false",
                    bookscore: book_score.value,
                    bookstock: book_stock.value,
                    bookpublisher: borrowed_book_publisher.value,
                },
                success() {
                    $.ajax({
                        url: 'http://47.121.28.202:8000/settings/getbooks/',
                        type: "PATCH",
                        data: {
                            book_id: borrowed_book_id.value,
                            stock: book_stock.value - 1,
                            score: book_score.value + 10,
                        },
                        success() {
                            close();
                            // window.location.reload(); 
                            $.ajax({
                                url: "http://47.121.28.202:8000/settings/borrowedbooks/",
                                type: "GET",
                                data: {
                                    user_id: store.state.user.id,
                                },
                                headers: {
                                    'Authorization': "Bearer " + store.state.user.access,
                                },
                                success(resp) {
                                    borrowedbooks.value = resp;
                                }
                            })
                        }
                    })
                }
            })
        }

        const return_add_score = () => {
            const is_have_the_book = ref(false);
            for (let i of book_user_ranking.book_user_ranking) {
                if(i.book_title === return_bookname.value) {
                    is_have_the_book.value = true;
                }
            }
            if (is_have_the_book.value) {
                $.ajax({
                    url: 'http://47.121.28.202:8000/settings/ranking/',
                    type: "PATCH",
                    headers: {
                        'Authorization': "Bearer " + store.state.user.access,
                    },
                    data: {
                        book_score: parseInt(return_book_score.value) + 4,
                        book_id: return_book_id.value,
                        user_id: store.state.user.id,
                        visittime: formattedDate,
                    },
                    success(resp) {
                        console.log(resp);
                    }
                })
            } else {
                $.ajax({
                    url: 'http://47.121.28.202:8000/settings/ranking/',
                    type: "POST",
                    headers: {
                        'Authorization': "Bearer " + store.state.user.access,
                    },
                    data: {
                        user_id: store.state.user.id,
                        book_id: parseInt(return_book_id.value),
                        book_title: return_bookname.value,
                        user_username: store.state.user.username,
                        visittime: formattedDate,
                        photo: return_book_photo.value,
                        author: return_book_author.value,
                        description: return_book_description.value,
                        book_type: return_book_type.value,
                        book_awarded: return_book_awarded.value,
                    },
                    success(resp) {
                        console.log(resp);
                        $.ajax({
                            url: 'http://47.121.28.202:8000/settings/ranking/',
                            type: "PATCH",
                            headers: {
                                'Authorization': "Bearer " + store.state.user.access,
                            },
                            data: {
                                book_score: 10,
                                book_id: parseInt(return_book_id.value),
                                user_id: store.state.user.id,
                                visittime: formattedDate,
                            }
                        })
                    }
                })
            }   
        }

        const return_a_book = () => {
            return_add_score()
            $.ajax({
                url: "http://47.121.28.202:8000/settings/returnbook/",
                type: "GET",
                headers: {
                    'Authorization': "Bearer " + store.state.user.access,
                },
                success(resp) {
                    apply_return_list.value = resp;
                    const is_have = ref(false);
                    for (let i of apply_return_list.value) {
                        if (i.borrower_id === store.state.user.id && i.borrowed_id === parseInt(return_book_id.value)) {
                            is_have.value = true;
                            break;
                        }
                    }
                    if (!is_have.value) {
                        $.ajax({
                            url: "http://47.121.28.202:8000/settings/returnbook/",
                            type: "POST",
                            headers: {
                                'Authorization': "Bearer " + store.state.user.access,
                            },
                            data: {
                                bookname: return_bookname.value,
                                bookauthor: return_book_author.value,
                                borrower_id: store.state.user.id,
                                borrowed_id: parseInt(return_book_id.value),
                                returntime: formattedDate,
                                borrower_photo: store.state.user.photo,
                                stock: parseInt(return_book_stock.value),
                                borrower_name: store.state.user.nickname,
                                borrower_number: store.state.user.username,
                                borrower_classname: store.state.user.classname,
                                borrower_collegename: store.state.user.collegename,
                                borrowed_publisher: return_book_publisher.value,
                                borrowed_score: parseInt(return_book_score.value),
                            },
                            success() {
                                $.ajax({
                                    url: "http://47.121.28.202:8000/settings/applyreturn/",
                                    type: "PATCH",
                                    headers: {
                                        'Authorization': "Bearer " + store.state.user.access,
                                    },
                                    data: {
                                        user_id: store.state.user.id,
                                        book_id: parseInt(return_book_id.value),
                                        is_apply: "true",
                                    }
                                })
                            }
                        })
                        
                    } else {
                        $.ajax({
                            url: "http://47.121.28.202:8000/settings/returnbook/",
                            type: "PATCH",
                            headers: {
                                'Authorization': "Bearer " + store.state.user.access,
                            },
                            data: {
                                borrower_id: store.state.user.id,
                                borrowed_id: return_book_id.value,
                                returntime: formattedDate,
                            },
                        });
                        $.ajax({
                            url: "http://47.121.28.202:8000/settings/applyreturn/",
                            type: "PATCH",
                            headers: {
                                'Authorization': "Bearer " + store.state.user.access,
                            },
                            data: {
                                user_id: store.state.user.id,
                                book_id: parseInt(return_book_id.value),
                                is_apply: "true",
                            }
                        })
                    }
                }
            })
            close();
        }

        // $.ajax({
        //     url: "http://47.121.28.202:8000/settings/borrowedbooks/",
        //     type: "GET",
        //     data: {
        //         user_id: store.state.user.id,
        //     },
        //     headers: {
        //         'Authorization': "Bearer " + store.state.user.access,
        //     },
        //     success(resp) {
        //         borrowedbooks.value = resp;
        //     }
        // })

        const is_borrowed = (booktitle) => {
            for (let book of borrowedbooks.value) {
                if (book.bookname === booktitle) {
                    return true
                } 
            }
            return false;
        }
        return {
            LiteratureBooks,
            open_a_book,
            borrow_a_book,
            return_a_book,
            close,
            open,
            is_open,
            is_open_return,
            borrowedbooks,
            borrowed_bookname,
            return_bookname,
            open_return,
            is_borrowed,
            go_to_page,
            recently_visit_books,
            pageCount,
            currentIndex,
        }
    }
}
</script>

<style scoped>
span {
    margin-right: 25px;
}
.card_single {
    margin-bottom: 10px;
}
button {
    float: right;
}
.btn-success {
    margin-right: 10px;
}
.bottom_info {
    position: relative;
    top: 0px;
}
.tanchuang {
    position: fixed;
    top: 50%; 
    left: 50%;  
    transform: translate(-50%, -50%);  
    height: 350px;  
    width: 500px;  
    background-color: rgba(211, 211, 211, 0.5);
    z-index: 1000;  
    display: flex;
    align-items: center; 
    justify-content: center;  
    padding: 20px;  
    box-sizing: border-box;
    border-radius: 10px;
}
.btn-tanchuang {
    position: relative;
    top: 105px;
}
.btn-1 {
    position: relative;
    right: 137px;
}
.btn-2 {
    position: relative;
    left: -84px;
}
.mb-3 {
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: relative;
    left: 67px;
}
.form-control {
    margin-bottom: 15px;
    font-weight: 1000;
}
.info_confirm {
    font-size: 14px;
    margin-bottom: 5px;
}
.pagination {
    position: relative;
    left: 500px;
}
</style>